package com.lihepeng.leecode.classic.binarySearch;

import org.junit.Test;

import java.util.Arrays;

/**
 *给定一个按照升序排列的整数数组 nums，和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。
 *
 * 如果数组中不存在目标值 target，返回 [-1, -1]。
 *
 * 进阶：
 *
 * 你可以设计并实现时间复杂度为 O(log n) 的算法解决此问题吗？
 *
 * 来源：力扣（LeetCode）
 * 链接：https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array
 * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
 */
public class Solution34 {
    // 暴力解法
    public int[] searchRange(int[] nums, int target) {
        int [] arrs = {-1,-1};
        if (nums.length==0){
            return arrs;
        }
        if (nums[nums.length-1] == target){
            arrs[1] = nums.length-1;
        }
        if (nums[0] == target){
            arrs[0] = 0;
        }
        for (int i=0;i<nums.length ;i++){
            if (i-1>0 && nums[i]==target && nums[i-1]!=target){
                arrs[0] = i;
            }
            if (i+1<nums.length && nums[i]==target&&nums[i+1]!=target){
                arrs[1] = i;
            }

        }
        return arrs;
    }

    /**
     * 使用二分查找法 分别确定左边界的值和右边界的值
     * @param nums
     * @param target
     * @return
     */
    public int[] searchRange01(int[] nums, int target) {
        int left = lowerBound(nums,target);
        int right = supperBound(nums,target);
        if (left>right){
            return new int[]{-1,-1};
        }
        return new int []{left,right};
    }
    private int lowerBound(int []nums,int target){
        int left =0;
        int right = nums.length-1;
        while(left <= right){
            int mid = ((right - left)>>1)+left;
            if (nums[mid]<target){
                left = mid+1;
            }else {
                right = mid -1;
            }
        }
        return left;
    }
    private int supperBound(int []nums,int target){
        int left =0;
        int right = nums.length-1;
        while(left <=right){
            int mid = ((right - left)>>1)+left;
            if (nums[mid]>target){
                right = mid -1;

            }else {
                left = mid+1;
            }
        }
        return right;
    }

    @Test
    public void runTest(){
        int []arrs = {5,7,7,8,8,10};
        System.out.println(lowerBound(arrs,8));
        System.out.println(supperBound(arrs,8));
        System.out.println(Arrays.toString(searchRange01(arrs,8)));

    }
}
